/**
 * 图片相关 素材图片 收藏图片 我的图片 上传图片
 */
/* eslint-disable no-undef */
define( [
  'jquery',
  'bigwe_utils',
  'api',
  '../../modules/createEditor',
  '../../lib/utils',
  'imgUploader',
  'bigwe_component',
  '../../lib/components'
], function( $, bu, api, editorObj, ut, iu, bc, components ) {
  var returnParam = {};

  var imgself = $( '.content-list .picture-div' );
  returnParam.pictureInit = function() {
    var initIndex = 2;
    if ( !picture[ initIndex ][ 'firstPicLoad' + initIndex ] ) {
      picture[ initIndex ].ajaxRequest();
      picture[ initIndex ][ 'firstPicLoad' + initIndex ] = !0;
      $( '.picture-detail>div', imgself ).eq( initIndex ).show().siblings().hide();
    }
    //$( '[event-columns] ul li', imgself ).eq( 0 ).trigger( 'click' );
  };
  // 上传成功的回调
  iu.init( $( '#my_upload_sourcetab' ).tooltip( {
    container: 'body'
  } )[ 0 ].id, function( paramData ) {
    //var myPictureDom = $( '.picture-boutique', imgself );

    var myPicture = picture[ 2 ];
    /*total = myPicture.total + 1
     newPageCount = parseInt( total / myPicture.searchParam.l ),
    oldPageCount = $( '.pageControl .maxPage', myPictureDom ).data( 'maxPage' ),
    currentPage = $( '.pageControl .currentPage', myPictureDom ).data( 'currentPage' ); */

    /*if (total % myPicture.searchParam.l) {
    	++newPageCount;
    }
    // 如果插入后页码增加了 需要刷新页码
    if (currentPage == 1) {

    }
    if (newPageCount > oldPageCount) {
    } else {
    	if (currentPage == oldPageCount) {
    		$('.picture-boutique .img_list', imgself).append(myPicture.getHtml([paramData.image]));
    	}
    }*/

    myPicture.resetPage = 0;
    myPicture.ajaxRequest();

    ut.comInsertImage.call( editorObj, {
      src: paramData.image,
      alt: paramData.title
    } );
  }, {
    auto_start: true,
    multi_selection: true
  } );

  imgself.show();
  $( '[event-columns="picture"]', imgself ).bwColumns( [ '我的图片', '我的收藏', '素材图片' ], function( index ) {
    var reverse = [ 2, 1, 0 ];
    index = reverse[ index.index() ];
    $( '.picture-detail>div', imgself ).eq( index ).show().siblings().hide();
    if ( !picture[ index ][ 'firstPicLoad' + index ] ) {
      picture[ index ].ajaxRequest();
      picture[ index ][ 'firstPicLoad' + index ] = !0;
    }
  } );
  imgself.hide();

  $( '.picture-detail', imgself ).on( 'click', '#batch_delete', function() {

    $( '.js_img_batch_delete_hide', imgself ).addClass( 'hide' );
    $( '.js_img_batch_delete', imgself ).removeClass( 'hide' );
    $( '.picture-boutique .img_list', imgself ).removeClass( 'filterwrapopen' ).addClass( 'batch_delete_open' );

  } ).on( 'click', '#batch_delete_cancel', function() {

    $( '.js_img_batch_delete', imgself ).addClass( 'hide' );
    $( '.js_img_batch_delete_hide', imgself ).removeClass( 'hide' );
    $( '.picture-boutique .img_list', imgself ).addClass( 'filterwrapopen' ).removeClass( 'batch_delete_open' );

  } ).on( 'click', '#batch_delete_sure', function() {
    var deleteParam = $( '.picture-boutique .img_list .img_item_wrap.selected', imgself ).map( function() {
      return $( this ).data( 'cd' );
    } ).get();
    if ( deleteParam.length ) {
      bc.deleteConfirmShowBottom( {
        obj: this,
        type: 'get',
        text: '确定要删除这' + deleteParam.length + '张图片吗？',
        url: api.MY_PICTURE.DELETE_IMG,
        param: {
          cd: deleteParam.join( ',' )
        },
        fun: function( data ) {
          // 我的图片对象
          var myPicture = picture[ 2 ];
          data = typeof data === 'string' ? JSON.parse( data ) : data;
          if ( data.ret === 0 ) {
            myPicture.resetPage = 0;
            myPicture.ajaxRequest();
            $( '#batch_delete_cancel', imgself ).trigger( 'click' );
          }
        }
      } );
    }
  } ).on( 'click', '.delete_choose', function() {
    $( this ).parent().toggleClass( 'selected' );
  } );

  imgself.on( 'keydown', '.js_img_search_ipt', function( e ) {
    e = e || event;
    if ( e.keyCode == 13 ) {
      $( '.js_btn_img_search', $( this ).parent() ).trigger( 'click' );
    }
  } ).on( 'click', '.js_btn_img_search', function() {
    var currentIndex = $( this ).parent().parent().index(),
      key = $.trim( $( '.js_img_search_ipt', imgself ).eq( currentIndex ).val() ),
      picObj = picture[ currentIndex ];

    picObj[ 'resetPage' ] = 0;
    picObj.ajaxRequest( {
      key: key
    } );
    $( '.img_list', imgself ).eq( currentIndex ).empty();
    $( '.js_dynamicHeight .pageControl', imgself ).eq( currentIndex ).hide();
    // extend原理
  } );

  function imageScrollTop( target ) {
    this.animate( {
      scrollTop: $( '.' + target, this ).position().top - this.find( '.img_list' ).offset().top - 174
    } );
  }

  var picture = [ { // 素材图片
    searchParam: {
      p: 1,
      key: '',
      l: 30,
      type: 'image'
    },
    ajaxRequest: function( option ) {
      var self = this;
      var $renderTarget = $( '.picture-resource .img_list', imgself );
      $.extend( self.searchParam, option );

      var anchor = 'anchor-page' + self.searchParam.p;
      if ( $( '.' + anchor, $renderTarget ).length ) {
        imageScrollTop.call( $renderTarget.parent(), anchor );
        return;
      }
      $( '.spinner.sp1', imgself ).show();
      $( '.picture-resource .nodatatips', imgself ).hide();
      //$( '.picture-resource .img_list', imgself ).empty();
      return $.ajax( {
        url: api.SEARCH.SEARCH_LIST,
        data: self.searchParam,
        type: 'post',
        success: function( data ) {
          data = typeof data == 'string' ? $.parseJSON( data ) : data;
          if ( !self.resetPage ) {
            self.pageChangeRander( data.data.total_rows );
            self.resetPage = !0;
          }
          if ( !data.data.data || !data.data.data.length ) {
            $( '.picture-resource .nodatatips', imgself ).show();
          }
          //$( '.picture-detail', imgself ).scrollTop( 0 );
          imageScrollTop.call( $renderTarget.append( self.getHtml( data.data.data, anchor, self.searchParam.p ) ).parent(), anchor );
          $( '.spinner.sp1', imgself ).hide();
        }
      } );
    },
    getHtml: function( arr, anchor, page ) {
      var newArray = [];
      arr.forEach( function( item ) {
        newArray.push( {
          image_id: item.cd,
          title: item.title,
          img_url: item.img_url
        } );
      } );

      var html = '<span class="' + anchor + '"></span>' + components.imgListComponents( newArray, true, {
        'data-page': page
      } );
      html = $( html );
      $( '[data-toggle="tooltip"]', html ).tooltip( {
        container: 'body'
      } );

      return html;
    },
    pageChangeRander: function( total ) {
      var self = this,
        pageObj = $( '.picture-resource .pageControl', imgself ),
        totalPage = parseInt( total / self.searchParam.l );

      if ( total % self.searchParam.l > 0 ) {
        ++totalPage;
      }
      if ( totalPage < 2 ) {
        pageObj.hide();
      } else {
        pageObj.show();
      }

      pageObj.bwPagination( {
        total: total,
        pageCount: self.searchParam.l,
        callback: function( index ) {
          self.ajaxRequest( {
            p: index
          } );
        }
      } );
    }
  }, { // 收藏的图片
    searchParam: {
      p: 1,
      key: '',
      l: 30
    },
    ajaxRequest: function( option ) {
      var self = this;
      $.extend( self.searchParam, option );
      $( '.spinner.sp2', imgself ).show();
      $( '.picture-collection .nodatatips', imgself ).hide();
      $( '.picture-collection .img_list', imgself ).empty();
      $.ajax( {
        url: api.MYCOLLECTION.COLLECT_IMG_LS,
        data: self.searchParam,
        type: 'post',
        success: function( data ) {
          data = typeof data === 'string' ? $.parseJSON( data ) : data;
          if ( !self.resetPage ) {
            self.pageChangeRander( data.data.total );
            self.resetPage = !0;
          }
          if ( !data.data.images || !data.data.images.length ) {
            if ( self.searchParam.key ) {
              $( '.picture-collection .search_none', imgself ).show();
            } else {
              $( '.picture-collection .self_none', imgself ).show();
            }
          }
          $( '.picture-detail', imgself ).scrollTop( 0 );
          $( '.picture-collection .img_list', imgself ).html( self.getHtml( data.data.images ) );
          $( '.spinner.sp2', imgself ).hide();
        }
      } );
    },
    getHtml: function( arr ) {
      var html = components.imgListComponents( arr );
      html = $( html );
      $( '[data-toggle="tooltip"]', html ).tooltip( {
        container: 'body'
      } );
      return html;
    },
    pageChangeRander: function( total ) {
      var self = this,
        pageObj = $( '.picture-collection .pageControl', imgself ),
        totalPage = parseInt( total / self.searchParam.l );

      if ( total % self.searchParam.l > 0 ) {
        ++totalPage;
      }
      if ( totalPage < 2 ) {
        pageObj.hide();
      } else {
        pageObj.show();
      }

      pageObj.bwPagination( {
        total: total,
        pageCount: self.searchParam.l,
        callback: function( index ) {
          self.ajaxRequest( {
            p: index
          } );
        }
      } );
    }
  }, { // 我的图片
    searchParam: {
      p: 1,
      key: '',
      l: 30
    },
    loadedPage: 0,
    isLoading: true,
    ajaxRequest: function( option ) {
      var self = this;
      var $renderTarget = $( '.picture-boutique .img_list', imgself );
      $.extend( self.searchParam, option );
      var anchor = 'anchor-page' + self.searchParam.p;
      //$( '.picture-boutique .img_list', imgself ).empty();
      if ( $( '.' + anchor, $renderTarget ).length ) {
        imageScrollTop.call( $renderTarget.parent(), anchor );
        return;
      }
      $( '.picture-boutique .nodatatips', imgself ).hide();
      $( '.spinner.sp3', imgself ).show();
      self.isLoading = true;
      $.ajax( {
        url: api.MY_PICTURE.MY_IMG,
        data: self.searchParam,
        type: 'post',
        success: function( data ) {
          self.isLoading = false;
          data = typeof data == 'string' ? $.parseJSON( data ) : data;
          if ( !self.resetPage ) {
            self.pageChangeRander( data.data.total, self.searchParam.p );
            self.resetPage = !0;
          }
          if ( self.searchParam.p == 1 ) {
            if ( !data.data.images || !data.data.images.length ) {
              if ( self.searchParam.key ) {
                $( '.picture-boutique .search_none', imgself ).show();
              } else {
                $( '.picture-boutique .self_none', imgself ).show();
              }
            } else {
              self.loadedPage++;
            }

          }
          self.total = data.data.total;
          //$( '.picture-detail', imgself ).scrollTop( 0 );
          imageScrollTop.call( $renderTarget.append( '<span class="' + anchor + '"></span>' + self.getHtml( data.data.images ) ).parent(), anchor );

          $( '.spinner.sp3', imgself ).hide();
        }
      } );
    },
    getHtml: function( arr ) {
      var html = components.imgListComponents( arr, false );
      $( '[data-toggle="tooltip"]', html ).tooltip( {
        container: 'body'
      } );
      return html;
    },
    pageChangeRander: function( total, currentPage ) {
      var self = this,
        pageObj = $( '.picture-boutique .pageControl', imgself ),
        totalPage = parseInt( total / self.searchParam.l );

      if ( total % self.searchParam.l > 0 ) {
        ++totalPage;
      }
      if ( totalPage < 2 ) {
        pageObj.hide();
      } else {
        pageObj.show();
      }

      pageObj.bwPagination( {
        total: total,
        pageCount: self.searchParam.l,
        currentPage: currentPage,
        callback: function( index ) {
          self.ajaxRequest( {
            p: index
          } );
        }
      } );
    }
  } ];

  $( '.picture-boutique .edit_scroll', imgself ).on( 'scroll', function() {

  } ).scrollMax( function() {
    if ( !picture[ 2 ].isLoading ) {
      $( this ).parent().find( '.pageControl' ).trigger( 'nextPage' );
    }
  } );
  return returnParam;
} );